package com.qigao.mall.service.core;

import com.qigao.mall.commons.dto.UserModiPassDto;
import com.qigao.mall.commons.dto.UserRegisterDto;
import com.qigao.mall.commons.enums.*;
import com.qigao.mall.commons.exceptions.BusinessException;
import com.qigao.mall.commons.utils.DateUtil;
import com.qigao.mall.commons.utils.IDUtils;
import com.qigao.mall.commons.utils.MD5Util;
import com.qigao.mall.config.EmailProperties;
import com.qigao.mall.jdbc.mapper.SysUserMapper;
import com.qigao.mall.jdbc.model.SysUser;
import com.qigao.mall.service.channel.MailService;
import com.qigao.mall.service.channel.RegisterTemplate;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author luiz
 * @Title: LoginCoreService
 * @ProjectName iot
 * @Description: TODO
 * @date 2019-04-04 15:19
 */
@Service
public class LoginCoreService {
    private static final Logger logger = LoggerFactory.getLogger(LoginCoreService.class);

    @Resource
    private SysUserMapper sysUserMapper;

    @Value("three.pass.salt:123456!@#123QweAsd")
    private String threePassSalt;

    @Resource
    private MailService mailService;
    @Resource
    private EmailProperties emailProperties;

    @Autowired
    private DataSourceTransactionManager transactionManager;

    public Result doRegister(UserRegisterDto userRegisterDto){
        List<SysUser> tkUsers=sysUserMapper.selectByCond(userRegisterDto);
        if(tkUsers!=null && tkUsers.size()>=1){
            return Result.newError(ResultCode.USER_HAS_EXISTS);
        }
        String randomStr=IDUtils.genIdStr("RG")+"$"+RandomStringUtils.randomAlphabetic(20);
        String activeUrl=emailProperties.getRegisterActiveUrl()+randomStr;
        String emailAddr=userRegisterDto.getEmailAddr();
        String registerConfirm= RegisterTemplate.registerConfirm(emailProperties.getSysName(),emailAddr,activeUrl);
        //发送邮件确认
        mailService.sendHtmlMail(emailAddr,"请激活您的账号",registerConfirm);

        DefaultTransactionDefinition defaultTransactionDefinition=new DefaultTransactionDefinition();
        defaultTransactionDefinition.setName(TransactionTypeEnum.RETISTER_USER.getCode());
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus transactionStatus=transactionManager.getTransaction(defaultTransactionDefinition);
        String userNo= IDUtils.genIdStr(IdTypeEnum.USER.getCode());
        try{
            SysUser sysUser=new SysUser();
            sysUser.setUserNo(userNo);
            String loginPass= MD5Util.genPass(userRegisterDto.getPass1(),threePassSalt);
            sysUser.setNickName(userRegisterDto.getNickName());
            sysUser.setLoginPass(loginPass);
            sysUser.setEmailAddr(userRegisterDto.getEmailAddr());
            sysUser.setStatus(StatusEnum.UNVALID.getCode());
            sysUser.setResv1(randomStr);
            sysUser.setCreateTime(new Date());
            sysUser.setModiTime(new Date());
            sysUserMapper.insertSelective(sysUser);
            transactionManager.commit(transactionStatus);
        }catch (Exception e){
            logger.error("注册账户异常:{}",e);
            transactionManager.rollback(transactionStatus);
            throw  new BusinessException(ResultCode.USER_REGISTER_ERROR);
        }
        return Result.newSuccess(userNo);
    }

    public Result activeUser(String activeCode) {
        SysUser oldUser=sysUserMapper.selectByActiveCode(activeCode);
        if(oldUser==null){
            return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
        }
        Date activeOverTime=DateUtil.addDay(oldUser.getCreateTime(),3);
        if(oldUser.getCreateTime()==null || activeOverTime.compareTo(new Date())<0){
            logger.warn("激活时间已过时,请重新操作{}",oldUser);
            return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
        }
        oldUser.setStatus(StatusEnum.VALID.getCode());
        sysUserMapper.updateByPrimaryKeySelective(oldUser);
        return Result.newSuccess();
    }




    public Result<String> resetPass(String userNo) {
        SysUser sysUser = sysUserMapper.selectByUserNo(userNo);
        if (sysUser == null) {
            return Result.newError(ResultCode.USER_NOT_EXISTS);
        }
        String initPass = RandomStringUtils.randomAlphanumeric(8);
        logger.info("账号:{}的密码已经被重置为:{}", userNo, initPass);
        sysUser.setLoginPass(MD5Util.genPass(initPass, threePassSalt));
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        return Result.newSuccess();
    }


    public Result forgetPass(String emailAddr) {
        //生成链接，发送到用户邮箱
        String randomStr=IDUtils.genIdStr(IdTypeEnum.USER.getCode())+"$"+RandomStringUtils.randomAlphabetic(20);
        SysUser sysUser = sysUserMapper.selectByEmailAddr(emailAddr);
        if (sysUser == null) {
            return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
        }
        sysUser.setResv1(randomStr);
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        //发送邮件
        String activeUrl=emailProperties.getForgetUrl()+"?activeCode="+randomStr;
        String registerConfirm= RegisterTemplate.forgetPass(emailProperties.getSysName(),emailAddr,activeUrl);
        mailService.sendHtmlMail(sysUser.getEmailAddr(),"请重新设置您的密码",registerConfirm);
        return Result.newSuccess();
    }


    public Result modiForgetPass(UserModiPassDto userModiPassDto) {
        //用户拿到链接后 进行密码修改
        SysUser oldTkUser = sysUserMapper.selectByUserNo(userModiPassDto.getLoginNo());
        if (oldTkUser == null) {
            return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
        }
        if (!oldTkUser.getResv1().equals(userModiPassDto.getForgetRadomStr())) {
            return Result.newError(ResultCode.COMMON_UNVALID_URL);
        }
        SysUser tkUser = new SysUser();
        tkUser.setUserNo(oldTkUser.getUserNo());
        tkUser.setLoginPass(MD5Util.genPass(userModiPassDto.getPasswordNew1(), threePassSalt));
        sysUserMapper.updateByPrimaryKeySelective(tkUser);
        return Result.newSuccess();
    }


    public Result<String> openClose(String userNo) {
        SysUser oldUser = sysUserMapper.selectByUserNo(userNo);
        if (oldUser == null) {
            return Result.newError(ResultCode.COMMON_DATA_NOT_EXISTS);
        }
        SysUser updateUser =new SysUser();
        updateUser.setId(oldUser.getId());
        if(StatusEnum.VALID.getCode()==oldUser.getStatus()){
            updateUser.setStatus(StatusEnum.UNVALID.getCode());
        }else {
            updateUser.setStatus(StatusEnum.VALID.getCode());
        }
        sysUserMapper.updateByPrimaryKeySelective(updateUser);
        return Result.newSuccess();
    }
}
